from flask import Blueprint, request, jsonify
from ..controllers.parking_space import (
    create_parking_space,
    get_parking_spaces,
    get_parking_space,
    update_parking_space,
    delete_parking_space
)

parking_bp = Blueprint('parking', __name__, url_prefix='/parking')


@parking_bp.route('/add', methods=['POST'])
def create_parking_space_route():
    """创建车位"""
    try:
        data = request.get_json() or {}
        return create_parking_space(data)
    except Exception as e:
        return jsonify({'code': 500, 'message': '服务器内部错误', 'data': str(e)})


@parking_bp.route('/list', methods=['GET'])
def get_parking_spaces_route():
    """获取车位列表"""
    try:
        data = request.args.to_dict() or {}
        return get_parking_spaces(data)
    except Exception as e:
        return jsonify({'code': 500, 'message': '服务器内部错误', 'data': str(e)})


@parking_bp.route('/space', methods=['GET'])
def get_parking_space_route():
    """获取单个车位信息"""
    try:
        parking_space_id = request.args.get('id')
        if not parking_space_id:
            return jsonify({'code': 400, 'message': '车位ID不能为空'})
        
        # 验证ID是否为数字
        try:
            parking_space_id = int(parking_space_id)
        except ValueError:
            return jsonify({'code': 400, 'message': '车位ID格式不正确'})
        
        return get_parking_space(parking_space_id)
    except Exception as e:
        return jsonify({'code': 500, 'message': '服务器内部错误', 'data': str(e)})


@parking_bp.route('/update', methods=['POST'])
def update_parking_space_route():
    """更新车位信息"""
    try:
        data = request.get_json() or {}
        return update_parking_space(data)
    except Exception as e:
        return jsonify({'code': 500, 'message': '服务器内部错误', 'data': str(e)})


@parking_bp.route('/delete', methods=['POST'])
def delete_parking_space_route():
    """删除车位"""
    try:
        data = request.get_json() or {}
        parking_space_id = data.get('id')
        
        if not parking_space_id:
            return jsonify({'code': 400, 'message': '车位ID不能为空'})
        
        # 验证ID是否为数字
        try:
            parking_space_id = int(parking_space_id)
        except ValueError:
            return jsonify({'code': 400, 'message': '车位ID格式不正确'})
        
        return delete_parking_space(parking_space_id)
    except Exception as e:
        return jsonify({'code': 500, 'message': '服务器内部错误', 'data': str(e)})